package com.appcenter.application.service;

import com.appcenter.application.dto.users.UserAddrDto;
import com.appcenter.application.dto.users.UserDto;
import com.appcenter.application.expand.ObjectFinal;
import com.appcenter.application.input.user.*;
import com.appcenter.application.mapper.*;
import com.appcenter.application.model.Orgs;
import com.appcenter.application.model.UserAddrs;
import com.appcenter.application.model.Users;
import com.appcenter.application.output.user.*;
import com.appcenter.jz.unit.ObjectUnit;
import com.appcenter.jz.config.ErrorJsonResult;
import com.appcenter.jz.page.PagedResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static org.apache.http.util.TextUtils.isBlank;

@Service
public class UserService {
    @Autowired
    UsersMapper usersMapper;
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    UserAddrsMapper userAddrsMapper;
    @Autowired
    OrgUsersMapper orgUsersMapper;
    @Autowired
    OrgsMapper orgsMapper;
    @Autowired
    RoleUsersMapper roleUsersMapper;


    @Autowired
    ObjectFinal objectFinal;

    /**
     *  创建人:Coke
     *  备注: 创建用户信息
     *  时间: 2019/4/26 14:09 
     *  参数:
     */
    public CreateUserOutput CreateUser(CreateUserInput input) throws Exception {
        CreateUserOutput output = new CreateUserOutput();
        Users UserCode = usersMapper.getUsersByUserCode(input.getItem().getUserCode(),objectFinal.getDataEffectiveVersion());
        if (UserCode != null) {
            throw new ErrorJsonResult("1000083", "用户账号已存在！");
        }
        Users user = new Users();
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();

        user.setId(uuid);
        user.setUserCode(input.getItem().getUserCode());
        user.setUserName(input.getItem().getUserName());
        user.setPassword(ObjectUnit.MD5Encryption(input.getItem().getPassword()));
        user.setDingUserId(input.getItem().getDingUserId());
        user.setEmail(input.getItem().getEmail());
        user.setAccountIsDisabled(input.getItem().getAccountIsDisabled());
        user.setPhone(input.getItem().getPhone());
        user.setSex(input.getItem().getSex());
        user.setBirthday(input.getItem().getBirthday());
        user.setOfficePhone(input.getItem().getOfficePhone());
        user.setJobNumber(input.getItem().getJobNumber());
        user.setCardNo(input.getItem().getCardNo());
        if (input.getItem().getUserAddress() != null) {
            UserAddrDto curUserAddr = new UserAddrDto();
            curUserAddr.setId(input.getItem().getUserAddress().getProvinceCode() + "," + input.getItem().getUserAddress().getCityCode() + "," + input.getItem().getUserAddress().getAreaCode());
            curUserAddr.setName(input.getItem().getUserAddress().getProvinceName() + "," + input.getItem().getUserAddress().getCityName() + "," + input.getItem().getUserAddress().getAreaName());
            user.setCityCode(objectMapper.writeValueAsString(curUserAddr));
        }
        //添加用户信息
        usersMapper.insertSelective(user);
        if (input.getItem().getUserAddress() != null) {
            UserAddrs userAddrs = userAddrsMapper.getUserAddsByUserId(user.getId());
            if (userAddrs != null) {
                userAddrsMapper.deleteByPrimaryKey(userAddrs.getId());
            }
            UserAddrs curUserAddr = new UserAddrs();
            curUserAddr.setId(UUID.randomUUID().toString().replace("-", "").toLowerCase());
            curUserAddr.setUserId(user.getId());
            curUserAddr.setProvinceCode(input.getItem().getUserAddress().getProvinceCode());
            curUserAddr.setCityCode(input.getItem().getUserAddress().getCityCode());
            curUserAddr.setAreaCode(input.getItem().getUserAddress().getAreaCode());
            userAddrsMapper.insertSelective(curUserAddr);
            user.setUserAddress(curUserAddr);
        }
        UserDto item = new UserDto();
        BeanUtils.copyProperties(user,item);
        output.setItem(item);
        return output;
    }

    /**
     *  创建人:Coke
     *  备注: 获取用户信息
     *  时间: 2019/4/26 14:09 
     *  参数: 
     */
//    @Cacheable(value="basedata",keyGenerator = "ObjectKey")
    public GetDataUsersOutput GetDataUsers(GetDataUsersInput input) throws Exception {
        GetDataUsersOutput output = new GetDataUsersOutput();
        input.setVersionNo(objectFinal.getDataEffectiveVersion());

        PageHelper.startPage(input.getPage().getPageNo(), input.getPage().getPageSize(),"userCode");
        List<Users> ls = usersMapper.searchUsers(input);
        PageInfo<Users> page = new PageInfo<>(ls);

        List<UserDto> newls = new ArrayList<UserDto>();
        for (int i = 0; i < ls.size(); i++) {
            UserDto newDto=new UserDto();
            BeanUtils.copyProperties(ls.get(i),newDto);
            newls.add(newDto);
        }
        output.setItems(new PagedResult<UserDto>(newls, (int) page.getTotal()));
        return output;
    }

//    @Cacheable(value="basedata",keyGenerator = "ObjectKey")
    /**
     *  创建人:Coke
     *  备注: 加载用户信息
     *  时间: 2019/4/26 14:11 
     *  参数: 
     */
    public PageLoadOutput PageLoad(PageLoadInput input) throws Exception {
        PageLoadOutput output = new PageLoadOutput();
        input.setVersionNo(objectFinal.getDataEffectiveVersion());
        output.setItems(GetDataUsers(input).getItems());
        return output;
    }

    /**
     *  创建人:Coke
     *  备注: 修改用户
     *  时间: 2019/4/26 14:11 
     *  参数: 
     */
    public EditUserOutput EditUser(EditUserInput input) throws Exception {
        EditUserOutput output = new EditUserOutput();
        Users UserCode = usersMapper.getUsersByUserCodeNoId(input.getItem().getUserCode(), input.getItem().getId(),objectFinal.getDataEffectiveVersion());
        if (UserCode != null) {
            throw new ErrorJsonResult("1000083", "用户账号已存在！");
        }


        Users oldUser = usersMapper.getUserById(input.getItem().getId(),objectFinal.getDataEffectiveVersion());
        oldUser.setUserCode(input.getItem().getUserCode());
        oldUser.setUserName(input.getItem().getUserName());
        //oldUser.setPassword(ObjectUnit.MD5Encryption(input.getItem().getPassword()));
        oldUser.setDingUserId(input.getItem().getDingUserId());
        oldUser.setEmail(input.getItem().getEmail());
        oldUser.setAccountIsDisabled(input.getItem().getAccountIsDisabled());
        oldUser.setPhone(input.getItem().getPhone());
        oldUser.setSex(input.getItem().getSex());
        oldUser.setBirthday(input.getItem().getBirthday());
        oldUser.setOfficePhone(input.getItem().getOfficePhone());
        oldUser.setJobNumber(input.getItem().getJobNumber());
        oldUser.setCardNo(input.getItem().getCardNo());

        if (input.getItem().getUserAddress() != null) {
            UserAddrDto curUserAddr = new UserAddrDto();
            curUserAddr.setId(input.getItem().getUserAddress().getProvinceCode() + "," + input.getItem().getUserAddress().getCityCode() + "," + input.getItem().getUserAddress().getAreaCode());
            curUserAddr.setName(input.getItem().getUserAddress().getProvinceName() + "," + input.getItem().getUserAddress().getCityName() + "," + input.getItem().getUserAddress().getAreaName());
            oldUser.setCityCode(objectMapper.writeValueAsString(curUserAddr));
        }

        //修改用户信息
        usersMapper.updateByPrimaryKey(oldUser);
        if (input.getItem().getUserAddress() != null) {
            UserAddrs userAddrs = userAddrsMapper.getUserAddsByUserId(oldUser.getId());
            if (userAddrs != null) {
                userAddrsMapper.deleteByPrimaryKey(userAddrs.getId());
            }
            UserAddrs curUserAddr = new UserAddrs();
            curUserAddr.setId(UUID.randomUUID().toString().replace("-", "").toLowerCase());
            curUserAddr.setUserId(oldUser.getId());
            curUserAddr.setProvinceCode(input.getItem().getUserAddress().getProvinceCode());
            curUserAddr.setCityCode(input.getItem().getUserAddress().getCityCode());
            curUserAddr.setAreaCode(input.getItem().getUserAddress().getAreaCode());
            userAddrsMapper.insertSelective(curUserAddr);
            oldUser.setUserAddress(curUserAddr);
        }




        UserDto item = new UserDto();
        BeanUtils.copyProperties(oldUser,item);
        output.setItem(item);
        return output;
    }

    /**
     *  创建人:Coke
     *  备注: 删除用户信息
     *  时间: 2019/4/26 14:11 
     *  参数: 
     */
    public DeleteUserOutput DeleteUser(DeleteUserInput input) {
        DeleteUserOutput output = new DeleteUserOutput();
        //删除部门的用户信息
        orgUsersMapper.deleteOrgUserByUserId(input.getItem().getId());
        //删除角色的用户信息
        roleUsersMapper.deleteRoleUserByUserId(input.getItem().getId());
        //删除用户信息
        usersMapper.deleteByPrimaryKey(input.getItem().getId());
        //删除用户的地址信息
        userAddrsMapper.deleteUserAddrByUserId(input.getItem().getId());
        return output;
    }

    /**
     *  创建人:Coke
     *  备注: 修改用户状态
     *  时间: 2019/4/26 14:11 
     *  参数: 
     */
    public ChangeAccountStatusOutput ChangeAccountStatus(ChangeAccountStatusInput input) throws Exception {
        ChangeAccountStatusOutput output = new ChangeAccountStatusOutput();
        input.setVersionNo(objectFinal.getDataEffectiveVersion());
        Users user = null;
        if (input.getId() != null && input.getId().length() > 0) {
            usersMapper.changeAccountStatusById(input);

        } else if (input.getUserCode() != null && input.getUserCode().length() > 0) {
            usersMapper.changeAccountStatusByUserCode(input);
        }
        return output;
    }

    /**
     *  创建人:Coke
     *  备注: 重置用户密码
     *  时间: 2019/4/26 14:12 
     *  参数: 
     */
    public ResetPassWordOutput ResetPassWord(ResetPassWordInput input) throws Exception {
        ResetPassWordOutput output = new ResetPassWordOutput();
        Users  user = usersMapper.getUserById(input.getUserId(),objectFinal.getDataEffectiveVersion());
        if (user == null) {
            throw new ErrorJsonResult("1000084", "找不到用户！");
        }

        user.setPassword("cwe123456");
        usersMapper.updateByPrimaryKey(user);
        output.setResult("成功");
        return output;
    }
    //---------DicService-----------
//    @Cacheable(value="basedata",keyGenerator = "ObjectKey")
    /**
     *  创建人:Coke
     *  备注: 获取用户信息
     *  时间: 2019/4/26 14:12 
     *  参数: 
     */
    public GetUserOutput GetUser(GetUserInput input) throws Exception {
        GetUserOutput output = new GetUserOutput();
        input.setVersionNo(objectFinal.getDataEffectiveVersion());
        Users user=usersMapper.getUser(input);
        if(user!=null) {
            UserDto item = new UserDto();
            BeanUtils.copyProperties(user, item);
            output.setItem(item);
        }
        return output;
    }


//    @Cacheable(value="basedata",keyGenerator = "ObjectKey")
    /**
     *  创建人:Coke
     *  备注: 获取用户
     *  时间: 2019/4/26 14:12 
     *  参数: 
     */
    public GetUsersOutput GetUsers(GetUsersInput input) throws Exception {
        GetUsersOutput output = new GetUsersOutput();
        input.setVersionNo(objectFinal.getDataEffectiveVersion());
       if (isBlank(input.getRoleCode()) && isBlank(input.getOrgCode())  )
       {
           return output;
       }
       if (isBlank(input.getAppCode()))
       {
           input.setAppCode(null);
       }
        List<Users> ls=new ArrayList<Users>();
      //  if (!isBlank(input.getOrgCode()) && !isBlank(input.getJobId()))
      //  {
      //      ls=usersMapper.getsUsersByJobId(input);
      //  }
       // else {
            if (!isBlank(input.getOrgCode())) {
                List<Orgs> orgs = orgsMapper.getOrgsByOrgCode(input);
                String OrgCodePath = "";
                if (orgs.size() > 0) {
                    OrgCodePath = orgs.get(0).getOrgCodePath() + "/";
                }
                ls = usersMapper.getsUsersByOrgCode(input.getAppCode(), input.getOrgCode(), input.getIsOneLevel(), OrgCodePath, objectFinal.getDataEffectiveVersion());
            }
            if (!isBlank(input.getRoleCode())) {
                ls = usersMapper.getsUsersByRoleCode(input);
            }
    //    }


        List<UserDto> newls = new ArrayList<UserDto>();
        for (int i = 0; i < ls.size(); i++) {
            UserDto newDto=new UserDto();
            BeanUtils.copyProperties(ls.get(i),newDto);
            newls.add(newDto);
        }
        output.setItems(new PagedResult<UserDto>(newls, newls.size()) );
        return output;
    }

    /**
     *  创建人:Coke
     *  备注: 修改密码
     *  时间: 2019/4/26 14:13 
     *  参数: 
     */
    public ChangePasswordOutput ChangePassword(ChangePasswordInput input) throws Exception {
        ChangePasswordOutput output = new ChangePasswordOutput();
        if (isBlank(input.getNewPassword()))
            throw new ErrorJsonResult("","用户密码不能为空");
        Users user=null;
        if (!isBlank(input.getId())) {
            user=usersMapper.selectByPrimaryKey(input.getId());
        }
        else{
            Example example = new Example(Users.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userCode", input.getUserCode());
            criteria.andEqualTo("versionNo", objectFinal.getDataEffectiveVersion());
            user = usersMapper.selectOneByExample(example);
        }
        if (user==null)
            throw new ErrorJsonResult("","找不到用户");
        if (!user.getPassword().equals(input.getOldPassword()))
            throw new ErrorJsonResult("","用户密码不正确");
        usersMapper.ChangePassword(user.getId(),ObjectUnit.MD5Encryption(input.getNewPassword()),objectFinal.getDataEffectiveVersion());
        user.setPassword(input.getNewPassword());

        ////将操作存储到同步数据表

        UserDto item = new UserDto();
        BeanUtils.copyProperties(user,item);
        output.setItem(item);
        return output;
    }

    /**
     *  创建人:Coke
     *  备注: 修改密码
     *  时间: 2019/4/26 14:13 
     *  参数: 
     */
    public UpdatePasswordOutput UpdatePassword(UpdatePasswordInput input) throws Exception {
        UpdatePasswordOutput output = new UpdatePasswordOutput();
        if (!input.getNewPassword().equals(input.getNewPassword2()))
            throw new ErrorJsonResult("1000030","两次输入的新密码不同,无法修改");

        Example example = new Example(Users.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("userCode", input.getUserCode());
        criteria.andEqualTo("password", ObjectUnit.MD5Encryption(input.getOldPassword()));
        criteria.andEqualTo("versionNo", objectFinal.getDataEffectiveVersion());
        int count = usersMapper.selectCountByExample(example);
        if (count==0)
            throw new ErrorJsonResult("1000010","原密码错误");
        if (count>1)
            throw new ErrorJsonResult("1000020","服务器数据出现问题,请联系管理员");
        if (count == 1)
        {
            Users user=usersMapper.selectOneByExample(example);

            usersMapper.ChangePassword(user.getId(),ObjectUnit.MD5Encryption(input.getNewPassword()),objectFinal.getDataEffectiveVersion());
        }
        output.setResultCode("1000000");
        output.setResultMsg("密码修改成功,请使用新密码重新登录");
       // Users user=usersMapper.getUser(input);
     //   output.setItem(user);
        return output;
    }

//    @Cacheable(value="basedata",keyGenerator = "ObjectKey")
    /**
     *  创建人:Coke
     *  备注: 获取用户信息
     *  时间: 2019/4/26 14:13 
     *  参数: 
     */
    public GetUserInfosOutput  GetUserInfos(GetUserInfosInput input) throws Exception {
        GetUserInfosOutput output = new GetUserInfosOutput();
        Example example = new Example(Users.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", input.getUserIds());
        criteria.andEqualTo("versionNo", objectFinal.getDataEffectiveVersion());
        List<Users> ls=usersMapper.selectByExample(example);




        List<UserDto> newls = new ArrayList<UserDto>();
        for (int i = 0; i < ls.size(); i++) {
            UserDto newDto=new UserDto();
            BeanUtils.copyProperties(ls.get(i),newDto);
            newls.add(newDto);
        }
        output.setItems(new PagedResult<UserDto>(newls, newls.size()));
        return output;
    }

//    @Cacheable(value="basedata",keyGenerator = "ObjectKey")
    /**
     *  创建人:Coke
     *  备注: 查询用户
     *  时间: 2019/4/26 14:19
     *  参数: 
     */
    public SearchUsersOutput  SearchUsers(SearchUsersInput input) throws Exception {
        SearchUsersOutput output = new SearchUsersOutput();
        input.setVersionNo(objectFinal.getDataEffectiveVersion());
        PageHelper.startPage(input.getPage().getPageNo(),input.getPage().getPageSize(),"id desc");
        List<Users> ls = usersMapper.searchUsersList(input);
        List<UserDto> newls = new ArrayList<UserDto>();
        for (int i = 0; i < ls.size(); i++) {
            UserDto newDto=new UserDto();
            BeanUtils.copyProperties(ls.get(i),newDto);
            newls.add(newDto);
        }
        PageInfo<UserDto> page = new PageInfo<>(newls);
        output.setItems(new PagedResult<UserDto>(page.getList(),(int)page.getTotal()));
        return output;
    }

}
